import axios from 'axios'
import { Toast,Dialog  } from 'vant';
import router from '../router/index'
const config = {
   headers: {
     'Content-Type': 'application/json;charset=UTF-8'
   },
   // baseURL:'http://shouyin.rzkeji.com/api',
   timeout: 0,
   responseType: 'json',
   maxContentLength: -1,
   withCredentials:true,
  crossdomain:true,
 }
 const service = axios.create(config)
export default function ajax(url = '', params = {}, type = 'GET') {
     // 1. 定义promise对象
     let promise;
     return new Promise((resolve, reject)=>{
        // 2. 判断请求的方式
        if('GET' === type){
              // 2.1 拼接请求字符串
              let paramsStr = '';
              Object.keys(params).forEach(key =>{
                 paramsStr += key + '=' + params[key] + '&'
              });
              // 2.2 过滤最后的&
              if(paramsStr !== ''){
                 paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'));
                 // 2.3 完整路径
                  url += '?' + paramsStr;
              }
              
              
              // 2.4 发送get请求
              promise = service.get(url)
        }else if('POST' === type){
              promise = service.post(url, params)
        }
        // 3. 返回请求的结果
        promise.then((response)=>{
            resolve(response.data)
        }).catch(error => {
           reject(error)
        })
     })
}

var myInterceptor=service.interceptors.response.use(function (res) {
   if( res.data.data === 'no_login') {
      Toast.fail({
         message: res.data.message,
         duration:1500
       })
     if(is_weixn()){
         setTimeout(()=>{
            window.location.href="http://www.51wenyisheng.com/api/auth/weixin-login?state=meeting";
         },1500)
     }
 
   }
   return res
 });
 function is_weixn(){
   var ua = navigator.userAgent.toLowerCase();
   if(ua.match(/MicroMessenger/i)=="micromessenger") {
       return true;
   } else {
       return false;
   }
}